package com.example.test15_3;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = (ImageView) findViewById(R.id.image1);

        //创建一个线程用于从网络上获取图片
        new Thread(new Runnable() {
            @Override
            public void run() {
                //从网络上获取图片
                final Bitmap bitmap = getPicture("https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&fmt=auto&app=138&f=JPEG?w=632&h=500");
                try{
                    Thread.sleep(2000);//线程休眠2s
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                //发送一个Runnable对象
                iv.post(new Runnable() {
                    @Override
                    public void run() {
                        iv.setImageBitmap(bitmap);//在ImageView中显示从网络上获取到的图片
                    }
                });
            }
        }).start();//开启线程
    }
    /*
    *功能：根据网址获取图片对应的Bitmap对象
    * @param path
    * @return
     */
    public Bitmap getPicture(String path){
        Bitmap bm = null;
        try{
            URL url = new URL(path);//创建URL对象
            URLConnection conn = url.openConnection();//获取URL对象对应的链接
            conn.connect();//打开链接
            InputStream is = conn.getInputStream();//获取输入流对象
            bm = BitmapFactory.decodeStream(is);//根据输入流对象创建Bitmap对象
        }catch (MalformedURLException e1){
            e1.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return bm;
    }
}